package cn.com.lyb.core.handler;


import cn.com.lyb.core.exception.BizException;
import cn.com.lyb.core.response.ResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author wangchen
 */
@RestControllerAdvice
public class ResponseExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(ResponseExceptionHandler.class);

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResultDTO handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                         HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return ResultDTO.failed(e.getMessage());
    }

    /**
     * 业务异常
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    public ResultDTO handleBizException(BizException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生异常.", requestURI, e);
        String code = e.getCode();
        return ResultDTO.failed(code, e.getMessage());
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(BindException.class)
    public ResultDTO handleBindException(BindException e, HttpServletRequest request)
    {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ResultDTO.failed(message);
    }

    /**
     * 未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ResultDTO handleRuntimeException(RuntimeException e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return ResultDTO.failed(e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultDTO handleException(Exception e, HttpServletRequest request)
    {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResultDTO.failed(e.getMessage());
    }
}
